<template>
  <div class="device-tree">
    <!-- 搜索组件返回扁平 rows -->
    <SearchFilters v-model="flatList" />

    <!-- 展示分页树 -->
    <DeviceNode
      v-for="item in treeRows"
      :key="item.id"
      :node="item"
    />

    <!-- 分页 -->
    <div class="tree-pagination" v-if="totalRoots > pageSize">
      <el-pagination
        background
        layout="total, prev, pager, next, jumper, sizes"
        :total="totalRoots"
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[5,10,20,50]"
        @current-change="noop"
        @size-change="handleSizeChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import SearchFilters from './SearchFilters.vue'
import DeviceNode from './DeviceNode.vue'

/** SearchFilters 返回的扁平数据 */
const flatList = ref([])

/** 转换后的完整树结构 */
const allRoots = ref([])

/** 分页 */
const pageNum = ref(1)
const pageSize = ref(15)
const totalRoots = ref(0)

/** ✅ 监听 flatList 变化时重建父子关系 */
watch(flatList, (rows) => {
  if (!rows?.length) {
    allRoots.value = []
    totalRoots.value = 0
    return
  }

  // 过滤系统层
  const filtered = rows.filter(r => r.nodeType !== 'SYSTEM')

  // 构建映射
  const map = new Map()
  filtered.forEach(f => map.set(f.id, { ...f, children: [] }))

  const roots = []
  filtered.forEach(f => {
    const cur = map.get(f.id)
    if (!f.parentId || !map.has(f.parentId)) {
      roots.push(cur)
    } else {
      map.get(f.parentId).children.push(cur)
    }
  })

  // 为每个节点挂上模拟备件信息
  roots.forEach(d => attachMockSpares(d))

  allRoots.value = roots
  totalRoots.value = roots.length
  pageNum.value = 1 // 每次搜索重置分页
})

/** 当前页切片 */
const treeRows = computed(() => {
  const start = (pageNum.value - 1) * pageSize.value
  const end = start + pageSize.value
  return allRoots.value.slice(start, end)
})

function handleSizeChange() {
  pageNum.value = 1
}
function noop() {}

/** 模拟备件数据 */
function attachMockSpares(node) {
  node.spareInfos = [
    { id: node.id + '-s1', name: '传感器', code: 'SP001', stock: 8 },
    { id: node.id + '-s2', name: '电机', code: 'SP002', stock: 3 }
  ]
  if (node.children?.length) {
    node.children.forEach(attachMockSpares)
  }
}
</script>

<style scoped>
.tree-pagination {
  margin-top: 12px;
  display: flex;
  justify-content: flex-end;
}
 
</style>
